package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.FujAdapter;
import com.oa.android.entry.Fjian;
import com.oa.android.entry.Plan;
import com.oa.android.utils.FileMange;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;


/**
 *
 * 计划详情
 * @author -zouqh
 * 
 */
public class DetailsPlanActivity extends Activity implements OnClickListener {

	private ImageView close;
	private TextView title,emilTitle,tiem,form,content,sherePerson;
	private MyGridView gridView;
	private Plan plan;
	private String[] fuj;
	private FujAdapter adapter;
	private ScrollView myScrollView;
	private ProgressDialog progressDialog;
	private Dialog Jdialog;
	private FileMange fileMange;
	private   String filePath = Environment.getExternalStorageDirectory().getPath() + File.separator+"ZHOA"+ File.separator;
	List<Fjian> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		plan= (Plan) getIntent().getSerializableExtra("plan");
		setContentView(R.layout.details_plan_activity);
		close = (ImageView) findViewById(R.id.close);
		title = (TextView) findViewById(R.id.title_text);
		emilTitle= (TextView) findViewById(R.id.emilTitle);
		tiem= (TextView) findViewById(R.id.time);
		form= (TextView) findViewById(R.id.form);
		sherePerson= (TextView) findViewById(R.id.sherePerson);
		content= (TextView) findViewById(R.id.emilContent);
		gridView=(MyGridView)findViewById(R.id.gridview);
		myScrollView = (ScrollView)findViewById(R.id.myScrollView);
		myScrollView.smoothScrollTo(0, 20);
		title.setText("计划详情");
		fileMange=new FileMange(this);
		close.setOnClickListener(this);

		getFj();

		if (plan!=null){
			emilTitle.setText(plan.getTITLE());
			form.setText("创建人："+plan.getEMPNAME());
			sherePerson.setText("允许查看："+plan.getEMPNAMES());
			content.setText(Html.fromHtml(plan.getCONTENT()));
			tiem.setText(""+plan.getOPTIME());
//			if (Util.NoNull(plan.getFUJIANSTR())){
//				if (plan.getFUJIANSTR().contains("|")){
//					fuj=plan.getFUJIANSTR().split("\\|");
//				}else{
//					fuj=new String[]{plan.getFUJIANSTR()};
//				}
//				adapter=new FujAdapter(this,fuj);
//				gridView.setAdapter(adapter);
//
//			}
		}

		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.i("position===",""+position);
				if (!new File(filePath+list.get(position).getOLDNAME()).exists()){
					if (Util.NoNull(list.get(position).getNOWNAME())){

						String[] bs= list.get(position).getNOWNAME().split("/");
						StringBuffer brf = new StringBuffer();
						for (int i = 0; i < bs.length; i++) {
							if(i==bs.length-1){

								try {
									brf.append(URLEncoder.encode(bs[i],"UTF-8").replaceAll("\\+", "%20"));
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}else {
								brf.append(bs[i]).append("/");
							}

						}

						pointDialog("您需要下载此文件吗？",1,brf.toString(),list.get(position).getOLDNAME());
					}else{
						Toast.makeText(DetailsPlanActivity.this,"下载地址有误",Toast.LENGTH_SHORT).show();
					}
//					pointDialog("您需要下载此文件吗？",1,list.get(position).getNOWNAME(),list.get(position).getOLDNAME());
//					downloadFile(UConstants.URL_DOWN+fuj[position],filePath+fuj[position]);
				}else{
					pointDialog("您需要打开此文件吗？",0,list.get(position).getOLDNAME(),list.get(position).getOLDNAME());
//					openFile(new File(filePath+fuj[position]));
				}

			}
		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		Intent intent ;
		switch (v.getId()) {
		case R.id.close:
			finish();

			break;

		default:
			break;
		}
	}

	/**
	 * 提示
	 */
	private void pointDialog(String str, final int p, final String pat, final String odfile) {
		LayoutInflater inflaterDl = LayoutInflater.from(this);
		View layout = inflaterDl.inflate(R.layout.exti_dialog,
				null);
		// 对话框
		Jdialog = new Dialog(this);
		Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		Jdialog.show();

		Jdialog.setContentView(layout);
		TextView sure = (TextView) layout.findViewById(R.id.sureExti);
		TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
		TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
		dialogTitle.setText(str);
		sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
				Jdialog.cancel();
				if(p==1){
					downloadFile(UConstants.URL_DOWN+pat,filePath+odfile);
				}else{
					fileMange.openFile(new File(filePath+odfile));
				}




			}
		});
		cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Jdialog.dismiss();
			}
		});

	}


	private void downloadFile(final String url, String path) {
		progressDialog = new ProgressDialog(this);
		RequestParams requestParams = new RequestParams(url);
		requestParams.setSaveFilePath(path);
		x.http().get(requestParams, new Callback.ProgressCallback<File>() {
			@Override
			public void onWaiting() {
			}

			@Override
			public void onStarted() {
			}

			@Override
			public void onLoading(long total, long current, boolean isDownloading) {
				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progressDialog.setMessage("下载中...");
				progressDialog.show();
				progressDialog.setMax((int) total);
				progressDialog.setProgress((int) current);
			}

			@Override
			public void onSuccess(File result) {
				Toast.makeText(DetailsPlanActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
				progressDialog.dismiss();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				ex.printStackTrace();
				Toast.makeText(DetailsPlanActivity.this, "下载失败，文件不存在或网络出错！", Toast.LENGTH_SHORT).show();
				progressDialog.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {
			}

			@Override
			public void onFinished() {
			}
		});
	}


	//获取附件
	public void getFj() {
		Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
		progressDialog = ProgressDialog.show(this, null, "加载中...", true, false);
		RequestParams params = new RequestParams(UConstants.GET_FJLIST);
		params.addBodyParameter("LKind", "OA");
		params.addBodyParameter("TNAME", "ERPGZJH");
		params.addBodyParameter("XH", plan.getID());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Util.printLog("getDownRoute------------onSuccess-----", result);
				if (result.length() > 0) {
					try {
						JSONObject object = new JSONObject(result);
						boolean success = object.getBoolean("success");
//						String msg = object.getString("msg");
						if (success) {
							Gson gson = new Gson();
							Type lt = new TypeToken<List<Fjian>>() {
							}.getType();
							list = gson.fromJson(object.getString("rows").toString(), lt);
							if (list != null && list.size() > 0) {
								adapter=new FujAdapter(DetailsPlanActivity.this,list);
								gridView.setAdapter(adapter);
							}


						}
//
					} catch (JSONException e) {

						Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				}
				progressDialog.dismiss();

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

				Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
				progressDialog.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {

				Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
				Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
				progressDialog.dismiss();
			}

			@Override
			public void onFinished() {

			}
		});
	}

}
